import { useState } from "react";
import {
  Form,
  Input,
  Modal,
  Button,
  Row,
  Col,
  Spin,
  message,Radio,
} from "antd";
import MyPagination, { PageInfo } from "@/components/pagination";
import { getAddDataByMonthAndVersion ,exportAddDataByMonthAndVersion} from "@/api";
import MyTable from "@/components/table";
import "./index.less";
import { BaseAccountStaticList, MapKey } from "@/types"
import { DatePicker, Space,Select } from 'antd';
import type { SelectProps } from 'antd';
import { getToken, clearLocalDatas, USER_INFO, TOKEN, MENU } from "@/utils";


import axios from 'axios';
// 请求地址
const BASE_URL = import.meta.env.REACT_APP_API_BASEURL || "/api/xxxxx";

interface OptionType {
  label: string;
  value: string | number;
}
export default function VehicleStatistics () {
  const [pageData, setPageData] = useState<PageInfo>({ page: 1 });
  const [tableData, setData] = useState<BaseAccountStaticList>([]);
  const [tableCol, setCol] = useState<MapKey>([]);
  const [load, setLoad] = useState(true);
  const [total, setTotal] = useState(0);
  const [showModal, setShow] = useState(false);
  const [isExporting, setIsExporting] = useState(false);

// 声明状态变量
  const [versionList, setVersionList] = useState<string[]>(["WindLink6.0/OS"]);
  const [startMonth, setStartMonth] = useState<string | string[] | null>(null);
  const [endMonth, setEndMonth] = useState<string | string[] | null>(null);
  const [vin, setVin] = useState<string>();
  const param = {startMonth,endMonth,versionList,vin};


    
    const handleChange = (value: string[]) => {
      console.log(`selected ${value}`);
      setVersionList(value);
    };

    // 处理开始月份选择
    const handleStartChange = (date: string, dateString:  string | string[]) => {
      console.log("handleStartChange"+JSON.stringify(dateString));
      setStartMonth(dateString);
    };

    // 处理结束月份选择
    const handleEndChange = (date: string, dateString:  string | string[]) => {
      console.log("handleEndChange"+JSON.stringify(dateString));
      setEndMonth(dateString);
    };

    //下拉项
    const options: SelectProps['options'] = [];
    options.push({label: "windlink OS"    ,value: "windlink OS"});
    options.push({label: "windlink"       ,value: "windlink"});
    options.push({label: "WindLink6.0/OS" ,value: "WindLink6.0/OS"});
    options.push({label: "windlink X"     ,value: "windlink X"});
    options.push({label: "eπ windlinkOS"  ,value: "eπ windlinkOS"});
    options.push({label: "DNA S31"        ,value: "DNA S31"});

  // 获取列表
  const getDataList = (data: PageInfo) => {
    const requestParams = { ...data, ...param }; 
    console.info("getAddDataByMonthAndVersion::"+JSON.stringify(requestParams));
    getAddDataByMonthAndVersion(requestParams)
    .then((res) => {
      const { data, statusCode, statusMessage } = res;
      if (statusCode === "0" && data) {
        let { list, mapKey, total } = data;
        // mapKey = mapKey.map((i) => {
        //   if (i.key === "type_name")  i.width = 500;
        //   return i;
        // });
        setCol(mapKey);
        setTotal(total);
        setData(list.map((i) => ({ ...i, key: i.vin })));
        setLoad(false);
        return;
      }
    }).finally(() => {
      setLoad(false); //最终都要设置为false
    });
  };


  // 顶部搜索
  const search = () => {
    setPageData({ page: 1 })
    getDataList({ ...pageData, ...param});
  };  

  // 页码改版
  const pageChange = (pageData: PageInfo) => {
    getDataList({ ...pageData, ...param });
    setPageData(pageData);
  };


    
    //Export====================
    const [form] = Form.useForm();
    const [vinExport, setVinExport] = useState<string>();
    const [exportName, setExportName] = useState<string>("新增保有明细");
    const [sheet1Export, setExportSheet1Name] = useState<string>("2025年02月Windlink4.0-6.0新增明细");
    const [sheet2Export, setExportSheet2Name] = useState<string>("2025年02月Windlink4.0-6.0保有明细");

    const [sheetDate, setsheetDate]       = useState<string>("2025年02月");
    const [sheetVersion, setsheetVersion] = useState<string[]>(["WindLink6.0/OS"]);

    const [versionListExport, setVersionListExport] = useState<string[]>(["WindLink6.0/OS"]);
    const [monthExport, setmonthExport] = useState<string>();
    const paramExport = {monthExport,versionListExport,vinExport,exportName,sheet1Export,sheet2Export};
  
    const handleChangeExport = (date: string, dateString:  string | string[]) => {
      console.log("handleChangeExport"+JSON.stringify(dateString));
      dateString as string;
      const datea = new Date(date);
      const formattedDate = datea.toISOString().split('T')[0];
      setmonthExport(formattedDate);
      setsheetDate(formattedDate); 
    };

    const handleVersionChangeExport = (value: string[]) => {
      setVersionListExport(value);
      setsheetVersion(value);
    };
    
    const handleTableNameChangeExport = (event: React.ChangeEvent<HTMLInputElement>) => {
      setExportName(event.target.value);
    };
  
    const optionsExport: OptionType[] = [];
    optionsExport.push({ label: "保有数量" as string, value: "保有数量" });
    optionsExport.push({ label: "新增数量" as string, value: "新增数量" });

    const str1 = "保有明细";
    const str2 = "新增明细";
    const str3 = "新增保有明细";
  const exportExcel = async () => {
    try {
      if (isExporting) {
        message.warning('导出功能10秒1次，请稍后再试');
        return;
      }
  
      setIsExporting(true);
      message.success('开始导出数据');

    let token = getToken();
    if(token==null) return;
    
    
    if (!exportName) {
      alert('请输入表名');
      return;
    }
    if (versionListExport.length === 0) {
      alert('请选择车机版本号');
      return;
    }
    if (!monthExport || monthExport=='' || monthExport==null) { 
      alert('请选择月份');
      return;
    }
    console.log("handleChangeExport"+JSON.stringify(exportName));
    console.log("versionListExport"+JSON.stringify(versionListExport));
    console.log("monthExport"+JSON.stringify(monthExport));


    let sheetx = versionListExport.join(",");
    const [year, month] = sheetDate.split("-");
    const formattedDate = `${year}年${month.padStart(2, '0')}月`
    setExportSheet1Name(formattedDate + sheetx + str1);
    setExportSheet2Name(formattedDate + sheetx + str2);
    setExportName(formattedDate + sheetx + str3);

    //异步
    let url_in = BASE_URL+'/exportAddDataByMonthAndVersion';
      const response = await axios.post(url_in, paramExport, {
        headers: { 'Authorization': token },
        responseType: 'blob' 
      });
  
      // 创建一个下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', exportName+'.xlsx'); 
      document.body.appendChild(link);
      link.click();
  
      // 释放内存
      window.URL.revokeObjectURL(url);

      setTimeout(() => {setIsExporting(false);}, 10000); 
    } catch (error) {
      console.error('导出Excel失败:', error);
    } finally {
      setTimeout(() => {setIsExporting(false);}, 80000); 
    }
  };
  


  return (
    <div className="search-container">
      <Spin spinning={load}>
        <div className="top-form"
            style={{ 
              display: 'flex', 
              justifyContent: 'space-between', 
              alignItems: 'center',
              flexWrap: 'wrap' ,
              width: '100%' ,
              marginRight: 'auto'
            }}
        >
          <Space direction="horizontal">
             <Input 
                placeholder="输入vin" 
                allowClear 
                value={vin}
                onChange={(e) => setVin(e.target.value)} 
             />

              <Select
                mode="multiple"
                allowClear
                style={{ width: '100%', minWidth: '200px' }}
                placeholder="输入车机版本号"
                defaultValue={versionList}
                onChange={handleChange}
                options={options}
              />


              <DatePicker 
              style={{ width: '100%' }}
              prefix="初始"  
              onChange={handleStartChange} 
              picker="month" 
              />

              <DatePicker 
              style={{ width: '100%' }}
              prefix="结束" 
              onChange={handleEndChange} 
              picker="month" />


              <Button onClick={search} type="primary" className="submit-btn">
              搜索
              </Button>

              <Button onClick={() => setShow(true)} type="primary" className="submit-btn" >
              导出功能
              </Button>
          </Space>
        </div>

        <MyTable
          dataSource={tableData}
          columns={tableCol}
          pagination={false}
          saveKey="MyListSearch"
        />
        <MyPagination
          page={pageData.page}
          immediately={getDataList}
          change={pageChange}
          total={total}
        />
      </Spin>

      <Modal
        title="新增保有明细导出"
        open={showModal}
        onCancel={() => setShow(false)}
        footer={[]} // 去掉默认的“取消”和“确定”按钮
      >
        <div className="top-form"
            style={{ 
              display: 'flex', 
              justifyContent: 'space-between', 
              alignItems: 'center',
              flexWrap: 'wrap' ,
              width: '100%' ,
              marginRight: 'auto'
            }}
        >
          <Space direction="vertical">
          <Form form={form} layout="vertical">
              <Form.Item
                  name="tableName"
                  rules={[{ required: true, message: '请输入表名' }]}
                >
                  <Input 
                    placeholder="输入表名" 
                    allowClear 
                    defaultValue={exportName}
                    value={exportName}
                    onChange={handleTableNameChangeExport} 
                  />
                </Form.Item>
                
                <Form.Item
                  name="versions"
                  rules={[{ required: true, message: '请选择车机版本号' }]}
                >
                  <Select
                    mode="multiple"
                    allowClear
                    style={{ width: '100%', minWidth: '200px' }}
                    placeholder="输入车机版本号"
                    defaultValue={sheetVersion}
                    onChange={handleVersionChangeExport}
                    options={options}
                  />
                </Form.Item>
                
                <Form.Item
                  name="date"
                  rules={[{ required: true, message: '请选择月份' }]}
                >
                  <DatePicker 
                    style={{ width: '100%' }}
                    prefix="月份" 
                    onChange={handleChangeExport} 
                    picker="month" 
                  />
                </Form.Item>
          </Form>

              <Button onClick={exportExcel} type="primary" className="submit-btn">导出</Button>

          </Space>
        </div>
      </Modal>
    </div>
  );
}
VehicleStatistics.route = {
  [MENU_PATH]: "/dfdev/vehicleStatistics",
};
